#!/usr/bin/env python
"""
##############################################################################
# 用法：./visitor_cpall.py fromDir toDir trace?                               #
# 类似system/filetools/cpall.py，不过借助visitor类和os.walk；在传入遍历器的所有名称  #
# 之前将fromDir替换成toDir。                                                    #
##############################################################################
"""
import os
import sys
import time
from visitor import FileVisitor
from my_PP4E.system.filetools import cpall


class CpallVisitor(FileVisitor):

    def __init__(self, fromDir, toDir, trace=True):
        FileVisitor.__init__(self, trace=trace)
        self.fromDir = os.path.abspath(fromDir)
        self.lengthFrom = len(self.fromDir)
        toDir = os.path.join(toDir, os.path.basename(self.fromDir))
        self.toDir = toDir

    def run(self):
        FileVisitor.run(self, self.fromDir)

    def visitDir(self, dirPath):
        toPath = os.path.join(self.toDir, dirPath[self.lengthFrom + 1:])
        if self.trace:
            print('目录', dirPath, '->', toPath)
        os.mkdir(toPath)
        self.dirCount += 1

    def visitFile(self, filePath):
        toPath = os.path.join(self.toDir, filePath[self.lengthFrom + 1:])
        if self.trace:
            print('文件', filePath, '->', toPath)
        cpall.copyFile(filePath, toPath)
        self.fileCount += 1


def main():
    fromDir, toDir = sys.argv[1:3]
    trace = len(sys.argv) > 3
    copier = CpallVisitor(fromDir, toDir, trace)
    print('正在复制……')
    start = time.time()
    copier.run()
    finish = time.time()
    print('复制完成：')
    print('{} 个目录， {} 个文件'.format(copier.dirCount, copier.fileCount))
    print('用时：')
    print(finish - start, 's')


if __name__ == '__main__':
    main()
